package com.bbcare.sso.client;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;

public class AuthorizingFilter implements Filter {

    Logger logger = Logger.getLogger(AuthorizingFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        logger.info("【BBcare SSO Filter】");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 静态资源不拦截
        String url = request.getRequestURI();
        if (filter(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (appfilter(url)) {
            // app端传入 并且传入channel值
            // String channel = request.getParameter("channel");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 验证前端是否传递了sessionId，未传递则跳转登录
        String sessionId = request.getParameter("sessionId");
        if (sessionId == null) {
            response.setContentType("json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"data\":{},\"success\":false,\"code\":"
                    + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SESSION_ISNULL + ",\"msg\":\"sessionId不能为空\"}");
            // response.sendRedirect(unauthorizedUrl);
            return;
        }

        // 获取session里面账号信息，如果session没有账号信息则去redis抓
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute(Constants.SESSION_ACCOUNT_KEY);
        if (account == null || !sessionId.equals(account.getSessionID())) {
            account = AccountService.getInstance().getAccount(sessionId);
        } else {
            AccountService.getInstance().setSessionTimeout(sessionId);
        }
        // 验证session的Id与前端传的是否一致，一致则放行，不一致跳转到登录
        if (account != null && sessionId.equals(account.getSessionID())) {
            request.getSession().setAttribute(Constants.SESSION_ACCOUNT_KEY, account);
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            logger.info("【BBcare SSO Filter fail】");
            response.setContentType("json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"data\":{},\"success\":false,\"code\":"
                    + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SESSION_VALUEISNULL + ",\"msg\":\"session信息不存在，请退出重新登陆\"}");
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    public Boolean filter(String url) {
        if (url.indexOf(".js") != -1 || url.indexOf(".jpg") != -1 || url.indexOf(".png") != -1
                || url.indexOf(".gif") != -1 || url.indexOf(".css") != -1 || url.indexOf(".ico") != -1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 客户端上传影像文件接口不校验登陆信息
     * 
     * @param url
     * @return
     */
    public Boolean appfilter(String url) {
        String filterPath = PropertiesUtils.getProperty("filterKey");
        if (StringUtils.isBlank(filterPath)) {
            filterPath = "/imgClientApi/upload/uploadClientImg";
        }
        if (url.indexOf(filterPath) != -1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void destroy() {
    }

}
